<template>
  <view class="login p-50" v-if="!isLoading" :style="{ backgroundImage:'url('+$xyfun.image('/static/other/login.jpg')+')'}">
    <view class="title ts-48 m-t-50">{{isInfo?'完善信息':'欢迎来到'}}</view>
    <view class="logo">
      <image mode="widthFix" :src="common.appConfig.logo" v-if="common.appConfig.logo!==''"/>
    </view>

    <block v-if="isInfo">
      <view class="fill_bg">
        <view class="title ts-48 m-t-20">完善信息</view>
        <view class="user-list lh-100 flex p-b-15 m-b-2 ">
          <text class="list-name">头像</text>
          <view class="r m-l-auto">
            <!-- #ifdef MP-WEIXIN -->
            <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" style="overflow: visible">
              <image class="avatar" :src="avatar" v-if="avatar != ''"/>
              <text class="xyicon icon-right m-l-15"></text>
            </button>
            <!-- #endif -->

            <!-- #ifdef H5 -->
            <button @tap="chooseImage()" style="overflow: visible">
              <image class="avatar" :src="avatar" v-if="avatar != ''"/>
              <text class="xyicon icon-right m-l-15"></text>
            </button>
            <!-- #endif -->
          </view>

        </view>
        <view class="user-list lh-70 flex p-tb-15 m-b-2 ">
          <text class="list-name">昵称</text>
          <view class="flex r m-l-auto">
            <input class="br-10" style="background-color: #e3e3e3;" type="nickname" placeholder="请输入昵称~"
                   @blur="blurNickName" maxlength="50" v-model="nickname"/>
          </view>
        </view>
        <view class="user-list lh-70 flex p-tb-15 m-b-2 ">
          <text class="list-name">性别</text>
          <view class="flex r m-l-auto">
            <radio-group @change="genderChange">
              <label class="radio m-r-20">
                <radio class="tf07" color="#ed8c1b" value="0" :checked="gender==0"/>
                女</label>
              <label class="radio">
                <radio class="tf07" color="#ed8c1b" value="1" :checked="gender==1"/>
                男</label>
            </radio-group>
          </view>
        </view>
        <button class="ts-30 lh-30 p-25 tc-w m-t-50 tmb" @tap="profile()">确定
        </button>
      </view>
    </block>

    <block v-if="!isLogin">
      <!-- #ifdef H5 -->
      <view class="fill_bg">
        <view class="title ts-48 m-t-20">短信登录</view>
        <view class="m-t-10 m-b-50 ts-28">未注册手机将自动注册登录</view>

        <view class="user-list lh-70 flex p-tb-15 m-b-2">
          <text class="list-name">手机号</text>
          <view class="flex r m-l-auto">
            <input class="br-10" placeholder="请输入手机号" maxlength="50"
                   v-model="mobile"/>
          </view>
        </view>
        <view class="user-list lh-70 flex p-tb-15 m-b-2">
          <text class="list-name">验证码</text>
          <view class="flex r m-l-auto">
            <input class="br-10 " type="code" placeholder="请输入验证码"
                   maxlength="50" v-model="captcha"/>
          </view>
          <view class="code br-10 tc-w" @tap="smsSend">{{ codeText }}</view>
        </view>
        <button class="ts-30 lh-30 p-25 tc-w m-t-40 m-b-50 tmb" @tap="smsLogin()">
          登录
        </button>

        <view class="tips flex p-tb-30 tc m-t-30 lh-50" :style="'color:#808080;'">
          <view class="agree flex " @tap="isAgree=!isAgree">
            <text class="xyicon icon-radio-a ts-30 flex tb" v-if="isAgree"></text>
            <text class="xyicon icon-radio ts-30 flex tb" v-else></text>
            <text class="m-l-10">我已阅读并同意</text>
          </view>
          <text class="tm" @tap="see(1)">《用户隐私协议》</text>
          和
          <text class="tm" @tap="see(2)">《安全免责条款》</text>
        </view>
      </view>
      <!-- #endif -->

      <!-- #ifdef MP-WEIXIN -->
      <view class="login_module">

        <view class="login_button">
          <button v-if="isAgree" class="tmb" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">
            <text>手机号授权登录</text>
          </button>
          <button v-else class="tmb" @tap="$xyfun.msg('请阅读并同意《隐私政策》')">
            <text>手机号授权登录</text>
          </button>
        </view>

        <view class="tips flex p-tb-30 tc lh-50 tc-w">
          <view class="agree flex " @tap="isAgree=!isAgree">
            <text class="xyicon icon-radio-a ts-30 m-r-20 flex tb" v-if="isAgree"></text>
            <text class="xyicon icon-radio ts-30 m-r-20 flex tb" v-else></text>
          </view>
          <view style="width: 600rpx;text-align: left;">
            <text class="m-l-10">我已阅读并同意</text>
            <text class="tm" @tap="see(1)">《用户隐私协议》</text>
            和
            <text class="tm" @tap="see(2)">《安全免责条款》</text>
          </view>
        </view>

      </view>
      <!-- #endif -->

    </block>
  </view>
</template>
<script>
import { mapState} from 'vuex';
import graceChecker from '@/utils/graceChecker';
import http_config from '@/config/http';
export default {
  data() {
    return {
      isLoading: true,
      loginType:'',
      isLogin:false,
      isInfo:false,
      isAgree:false,

      mobile:'',
      avatar:'',
      nickname:'',
      gender: '0',
      captcha:'',
      userInfo:{},
      submitDisabled:false,
      disabledCode:false,
      codeText:'获取验证码',
      loginRes: {},
    };
  },
  computed: {
    ...mapState(['common','user'])
  },
  async onLoad() {


    if(this.user.isLogin){
      this.$xyfun.back('已经登录');
    }

    // 微信小程序code提前获取
    // #ifdef MP-WEIXIN
    uni.login({
      provider: 'weixin',
      success: res => {
        console.log(res);
        this.loginRes = res;
      },
      fail: err => {
        this.$xyfun.msg(err.msg);
      }
    });
    // #endif

    this.isLoading = false;


  },
  methods: {

    blurNickName(e) {
      if (e.detail.value) this.nickname = e.detail.value;
    },

    getUrlCode() {
      var url = location.search;
      var theRequest = new Object();
      if (url.indexOf('?') != -1) {
        var str = url.substr(1);
        var strs = str.split('&');
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
        }
      }
      return theRequest;
    },

    queryParams(data, isPrefix = false) {
      let prefix = isPrefix ? '?' : ''
      let _result = []
      for (let key in data) {
        let value = data[key]
        if (['', undefined, null].includes(value)) {
          continue
        }
        if (value.constructor === Array) {
          value.forEach(_value => {
            _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value))
          })
        } else {
          _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
        }
      }
      return _result.length ? prefix + _result.join('&') : ''
    },

    // 微信小程序手机号授权登录
    decryptPhoneNumber(e){
      this.$api.post({
        url: '/user/phone',
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          code: this.loginRes.code,
        },
        success: res => {
          //首次登录
          if(res.userInfo.is_info==1){
            this.userInfo = res.userInfo;
            this.$store.dispatch('user/login', res);
            this.isInfo = true;
            this.isLogin = true;
          }else{//之前登录过
            this.$store.dispatch('user/login', res);
            this.$Router.back();
          }
        }
      });
    },

    // 微信授权登录
    wecahtLogin(){
      if(this.isAgree){
        this.$api.post({
          url: '/user/wechat',
          data: {
            code: this.loginRes.code,
          },
          success: res => {
            //首次登录
            if(res.userInfo.is_info==1){
              this.userInfo = res.userInfo;
              this.$store.dispatch('user/login', res);
              this.isInfo = true;
              this.isLogin = true;
            }else{//之前登录过
              this.$store.dispatch('user/login', res);
              this.$Router.back();
            }
          }
        });
      }else{
        this.$xyfun.msg('请阅读并同意《隐私政策》');
      }
    },

    // 验证码登录
    smsLogin(){
      if(this.isAgree){
        var data = {
          mobile:this.mobile,
          captcha:this.captcha
        }
        //定义表单规则
        var rule = [
          { name: 'mobile', checkType: 'phoneno', errorMsg: '请填写正确的手机号' },
          { name: 'captcha', checkType: 'string', checkRule: '6,6', errorMsg: '请输入正确的验证码' },
        ];
        //进行表单检查
        var checkRes = graceChecker.check(data, rule);

        if (checkRes) {
          this.$api.post({
            url: '/user/smslogin',
            data:data,
            loadingTip: '登录中...',
            success: res => {
              if(res.userInfo.is_info == 1){
                this.userInfo = res.userInfo;
                this.isLogin = true;
                this.isInfo = res.userInfo.is_info;
                this.$store.dispatch('user/login', res);
                this.$xyfun.to('pages/index',true)
              }else{
                this.$store.dispatch('user/login', res);
                this.$xyfun.to('pages/index',true)
              }
            }
          });
        }else {
          this.$xyfun.msg(graceChecker.error);
        }
      }else{
        this.$xyfun.msg('请阅读并同意《隐私政策》');
      }
    },

    genderChange(e){
      this.gender = e.detail.value;
    },

    onChooseAvatar(e) {
      this.avatar = e.detail.avatarUrl;
      this.uploadImage(e.detail.avatarUrl);
    },

    // 图片处理-选择图片
    async chooseImage() {
      var that = this;
      console.log('选择图片');
      uni.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ['album','camera'],
        success: res => {
          that.uploadImage(res.tempFilePaths[0])
        }
      });
    },

    // 上传图片
    async uploadImage(url) {
      var that = this;
      uni.showLoading({
        title:'图片上传中...'
      })
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: http_config.base_url + '/addons/alioss/index/upload',
          filePath: url,
          name: "file",
          header: { token: that.userInfo.token },
          success: res => {
            res = JSON.parse(res.data);
            that.avatar = res.data.fullurl;
            resolve(res.data.fullurl);
          },
          complete: e => {
            uni.hideLoading();
          }
        });
      }).catch(e => {
        console.log(e);
      });
    },

    see(type){
      if(type==1){
        this.$xyfun.to('/pages/news/detail?id=19');
      }
      if(type==2){
        this.$xyfun.to('/pages/news/detail?id=23');
      }
    },

    smsSend(){
      if (this.disabledCode) return;
      var data = {
        mobile:this.mobile
      }
      //定义表单规则
      var rule = [
        { name: 'mobile', checkType: 'phoneno', errorMsg: '请填写正确的手机号' },
      ];
      //进行表单检查
      var checkRes = graceChecker.check(data, rule);

      if (checkRes) {
        this.$api.get({
          url: '/sms/send',
          data:{
            event: 'register',
            mobile: this.mobile
          },
          loadingTip: '验证码发送中...',
          success: res => {
            this.$xyfun.msg('验证码发送成功');
            this.codeChange();
          }
        });
      }else {
        this.$xyfun.msg(graceChecker.error);
      }


    },

    // 倒计时
    codeChange() {
      if (this.disabledCode) return;
      this.disabledCode = true;
      var n = 60;
      this.codeText = n + "s";
      const run = setInterval(() => {
        n -= 1;
        if (n < 0) {
          clearInterval(run);
        }
        this.codeText = n + "s";
        if (this.codeText < 0 + "s") {
          this.disabledCode = false;
          this.codeText = "重新获取";
        }
      }, 1000);
    },


    //完善信息
    profile(){

      var data = {
        avatar:this.avatar,
        nickname:this.nickname,
        gender:this.gender
      }

      //定义表单规则
      var rule = [
        { name: 'avatar', checkType: 'string', checkRule: '1,300', errorMsg: '头像不能为空' },
        { name: 'nickname', checkType: 'string', checkRule: '2,20', errorMsg: '昵称为2-20个字符' },
        { name: 'gender', checkType: 'in', checkRule: '0,1', errorMsg: '请选择性别' },
      ];

      //进行表单检查
      var checkRes = graceChecker.check(data, rule);

      if (checkRes) {
        this.$api.post({
          url: '/user/profile',
          loadingTip:'加载中...',
          data: {
            nickname: this.nickname,
            avatar: this.avatar,
            gender:this.gender
          },
          success: res => {
            this.$store.dispatch('user/login', res);
            this.$Router.back();
          }
        });
      }else {
        this.$xyfun.msg(graceChecker.error);
        this.submitDisabled = false;
      }


    },

  }
};
</script>

<style>
page{
  height: 100vh;
  overflow: hidden;
}
</style>
<style scoped lang="scss">
.login{
  background-size: cover;
  height: 100vh;
  overflow: hidden;
  background: #ffdcbe;
  .title{
    color: #fff;
  }
  .logo{
    margin-top: 30rpx;
    margin-bottom: 300rpx;
    image{
      width: 150rpx;
    }
  }
}
.login_module{
  position: fixed;
  bottom: 200rpx;
  left: 0;
  right: 0;
  margin: 0 auto;
  .login_button{
    button{
      height: 80rpx;
      line-height: 80rpx;
      width: 500rpx;
      color: #fff;
    }
  }
}

.fill_bg{
  background: rgba(255, 255, 255, 0.92);
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  box-sizing: border-box;
}

button::after {
  border: none;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
}

.user-list {
  flex-wrap: nowrap;

  .list-name {
    width: 20%;
    flex-shrink: 0;
  }

  .code {
    flex-shrink: 0;
    width: 180rpx;
    height: 78rpx;
    line-height: 78rpx;
    text-align: center;
    margin-left: 20rpx;
  }

  .r {
    width: 100%;

    input {
      width: 100%;
      vertical-align: middle;
      line-height: 78rpx;
      height: 78rpx;
      padding-left: 20rpx;
    }

    button {
      padding: 0;
      margin: 0;
      background: none;
      float: right;
      border-radius: 0;
      width: 100%;
      text-align: right;
    }
  }
}

.tips {
  justify-content: center;
}

.member button {
  border-radius: 40rpx;
  width: 300rpx;
}

.wechat {
  background: #3cb034;
}

.phone {
  background: #4b68f7;
}
</style>
